package flow

import (
	"context"
	"errors"
	"flow-calc/core"
	"fmt"
)

// dealAction 处理Action,决定Flow流程走向
func (flow *Flow) dealAction(ctx context.Context, fn core.Function) (core.Function, error) {
	// 校验是否复用数据
	var err error
	if flow.action.DataReuse {
		err = flow.commitReuseData(ctx)
	} else {
		err = flow.commitCurData(ctx)
	}
	if err != nil {
		return nil, err
	}
	// 强制进入下一层。
	if flow.action.ForceEntryNext {
		if err = flow.commitVoidData(ctx); err != nil {
			return nil, err
		}
		// 重置abort
		flow.abort = false
	}
	// JumpFunc 跳转到指定的Function(直接就是切换)
	if flow.action.JumpFunc != "" {
		if jumpFunction, ok := flow.Func[flow.action.JumpFunc]; !ok {
			return nil, errors.New(fmt.Sprintf("JumpFunc: %s is not exist", flow.action.JumpFunc))
		} else {
			// 更新上一层FunctionId游标
			flow.PrevFunctionId = jumpFunction.GetPrevId()
			fn = jumpFunction
			// 如果设置跳跃,中止重置
			flow.abort = false
		}
	} else {
		// 更新上一层FunctionId游标
		flow.PrevFunctionId = flow.ExecFunctionId
		fn = fn.NextF()
	}
	if flow.action.Abort {
		flow.abort = true
	}
	// 清空Action
	flow.action = core.Action{}
	return fn, nil
}
